package com.library.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.library.entity.User;
import com.library.mapper.UserMapper;
import com.library.service.UserService;
import com.library.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * 用户Service实现
 *
 * @author Library Team
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public User getByUsername(String username) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, username);
        return getOne(wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String login(String username, String password) {
        // 查询用户
        User user = getByUsername(username);
        if (user == null) {
            log.warn("登录失败：用户不存在 - {}", username);
            throw new RuntimeException("用户名或密码错误");
        }

        // 检查账户状态
        if (user.getStatus() == 0) {
            log.warn("登录失败：账户已被禁用 - {}", username);
            throw new RuntimeException("账户已被禁用");
        }

        // 验证密码
        if (!passwordEncoder.matches(password, user.getPassword())) {
            log.warn("登录失败：密码错误 - {}", username);
            throw new RuntimeException("用户名或密码错误");
        }

        // 生成JWT Token
        String token = jwtUtil.generateToken(user.getId(), user.getUsername(), user.getRole());
        log.info("用户登录成功 - {}", username);
        return token;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean register(String username, String password, String realName, String email) {
        // 检查用户名是否已存在
        User existUser = getByUsername(username);
        if (existUser != null) {
            log.warn("注册失败：用户名已存在 - {}", username);
            throw new RuntimeException("用户名已存在");
        }

        // 创建新用户
        User user = new User();
        user.setUsername(username);
        user.setPassword(passwordEncoder.encode(password));
        user.setRealName(realName);
        user.setEmail(email);
        user.setRole("USER");
        user.setStatus(1);

        return save(user);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateUser(User user) {
        // 查询原用户信息
        User oldUser = getById(user.getId());
        if (oldUser == null) {
            throw new RuntimeException("用户不存在");
        }

        // 设置更新时间，避免数据库约束违反
        user.setUpdatedAt(LocalDateTime.now());

        boolean result = updateById(user);
        if (result) {
            log.info("更新用户成功 - {}", user.getUsername());
        }
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteUser(Long id) {
        // 查询用户信息
        User user = getById(id);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        // 手动设置逻辑删除标记和更新时间，避免数据库约束违反
        user.setDeleted(1);
        user.setUpdatedAt(LocalDateTime.now());

        boolean result = updateById(user);
        if (result) {
            log.info("删除用户成功 - ID: {}", id);
        }
        return result;
    }

}
